package front

import (
	"github.com/juju/errors"
	"qihuang/config"
	"qihuang/db/mysql"
	"qihuang/db/redis"
	"qihuang/loger"
	"qihuang/model"
	"qihuang/protocol"
	"strconv"
	"time"
)

type KinParams struct {
	Id         int    `json:"id",gorm:"primary_key;AUTO_INCREMENT"`
	CreateTime string `json:"create_time"`
	ModifyTime string `json:"modify_time"`
	Status     int    `json:"status"`
	Deleted    int    `json:"deleted"`
	FamilyId   int    `json:"family_id"`
	DearId     int    `json:"dear_id"`
	Title      string `json:"title"`
	Content    string `json:"content"`
	Attention  string `json:"attention"`
}

type KinDetail struct {
	model.Kin
}

type Kin struct {
}

type KinList struct {
	Total    int         `json:"total"`
	Datalist []model.Kin `json:"datalist"`
}

//添加家庭成员
func (c *Kin) Add(params *KinParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "创建失败", Data: ""}
	family := model.Kin{
		Deleted:    0,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		DearId:     params.DearId,
		FamilyId:   params.FamilyId,
		Title:      params.Title,
		Content:    params.Content,
		Attention:  params.Attention,
	}

	db := mysql.Default().GetConn()
	defer db.Close()
	// 开始事务
	tx := db.Begin()
	//添加kin
	err := db.Model(model.Kin{}).Create(&family).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	//提交事务
	tx.Commit()
	resp.Status = 0
	resp.Msg = "创建成功"
	return resp
}

//更新成员信息
func (c *Kin) Update(id int, params *KinParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "更新失败", Data: ""}
	if err := c.deleteKinCache(id); err != nil {
		resp.Msg = "更新失败，请重试！"
		return resp
	}
	//查询ID是否存在
	db := mysql.Default().GetConn()
	defer db.Close()
	count := 0
	if err := db.Model(model.Kin{}).Where("id = ?", id).Count(&count).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}

	if count <= 0 {
		resp.Msg = "家庭成员不存在"
		return resp
	}
	articles := model.Kin{
		DearId:     params.DearId,
		FamilyId:   params.FamilyId,
		Title:      params.Title,
		Content:    params.Content,
		Attention:  params.Attention,
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
	}

	// 开始事务
	tx := db.Begin()
	//添加articles
	err := db.Model(model.Kin{}).Where("id = ?", id).Update(&articles).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	//提交事务
	tx.Commit()
	resp.Status = 0
	resp.Msg = "更新失败"
	return resp
}

//分页获取家庭成员列表
func (c *Kin) GetList(familyId int, page int, pageSize int, fields []string) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "获取列表信息失败", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	offset := (page - 1) * pageSize
	familyList := &KinList{}
	families := make([]model.Kin, 0)
	total := 0

	db.Model(&model.Kin{}).Count(&total)
	if err := db.Where("family_id=?", familyId).Offset(offset).Limit(pageSize).Order("id desc").Find(&families).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	familyList.Datalist = families
	familyList.Total = total
	resp.Status = 0
	resp.Msg = "获取列表成功"
	resp.Data = familyList
	return resp
}

//删除文章
func (c *Kin) Delete(id int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "删除失败", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	if err := c.deleteKinCache(id); err != nil {
		resp.Msg = "删除失败，请重试！"
		return resp
	}
	if err := db.Where("id = ?", id).Delete(&model.Kin{}).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	resp.Status = 0
	resp.Msg = "删除成功！"
	return resp
}

//文章详情
func (c *Kin) GetDetail(id int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	article := &model.Kin{}
	//article_content := &model.ArticlesContents{}

	if err := db.Where("id = ?", id).Find(article).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	detail := &KinDetail{}
	detail.Id = id
	detail.CreateTime = article.CreateTime
	detail.ModifyTime = article.ModifyTime
	detail.Status = article.Status
	detail.Deleted = article.Deleted
	detail.FamilyId = article.FamilyId
	detail.DearId = article.DearId
	detail.Title = article.Title
	detail.Content = article.Content
	detail.Attention = article.Attention
	resp.Data = detail
	resp.Status = 0
	return resp
}

func (c *Kin) deleteKinCache(id int) error {
	redisConn := redis.RedisClient.Pool.Get()
	cacheKey := "kin_" + config.Configs.RedisCacheVersion + ":" + strconv.Itoa(id)
	if err := redisConn.Err(); err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return err
	}
	_, err := redisConn.Do("del", cacheKey)
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return err
	}
	return nil
}
